package com.ziri.quartz.cluster.service.impl;

import com.ziri.quartz.cluster.entity.BaseLabel;
import com.ziri.quartz.cluster.entity.TaskEntity;
import com.ziri.quartz.cluster.service.QuartzService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class QuartzServiceImpl implements QuartzService {

    final int studentCount = 10021;//测试用
    @Autowired
    Scheduler scheduler;

    @Override
    public void initAllTask(List<BaseLabel> scheduledTaskBeanList) throws Exception {
        System.out.println("程序启动 ==> 初始化所有任务开始 ！");
        if (CollectionUtils.isEmpty(scheduledTaskBeanList)) {
            scheduler.shutdown();
            return;
        }
        for (BaseLabel baseLabel : scheduledTaskBeanList) {
            //拆分任务
            int taskCount = 0;
            taskCount = studentCount / baseLabel.getSingleCount() + (studentCount % baseLabel.getSingleCount() > 0 ? 1 : 0);
            for (int i = 0; i < taskCount; i++) {
                TaskEntity taskEntity = new TaskEntity();
                taskEntity.setGroup(baseLabel.getLabelCode());
                taskEntity.setName(baseLabel.getLabelName());
                taskEntity.setId(i);
                taskEntity.setMinId(baseLabel.getSingleCount() * i + 1);
                taskEntity.setMaxId(baseLabel.getSingleCount() * (i + 1));
                taskEntity.setHandlerClass(baseLabel.getHandleClass());
                this.addJob(taskEntity);
            }
            //this.addJob(baseLabel);
        }
        System.out.println("程序启动 ==> 初始化所有任务结束 ！");
    }

    @Override
    public void addJob(TaskEntity scheduledTask) {
        TriggerKey triggerKey = getTriggerKey(scheduledTask);
        //作业名称及分组
        JobKey jobKey = getJobKey(scheduledTask);
        try {
            Class<?> aClass = Class.forName(scheduledTask.getHandlerClass());
            //构建job信息
            JobDetail jobDetail = JobBuilder.newJob(((Job) aClass.newInstance()).getClass()).withIdentity(jobKey).build();
            SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.repeatSecondlyForever(2);//.withMisfireHandlingInstructionFireNow()
            //创建触发器
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withSchedule(simpleScheduleBuilder.withRepeatCount(0)).build();
            Map<String, Integer> paramMap = new HashMap<>();
            paramMap.put("minId", scheduledTask.getMinId());
            paramMap.put("maxId", scheduledTask.getMaxId());
            trigger.getJobDataMap().putAll(paramMap);
            scheduler.scheduleJob(jobDetail, trigger);

        } catch (Exception e) {
            System.out.println("addJob错误，" + e.getMessage());
        }
    }

    private TriggerKey getTriggerKey(TaskEntity baseLabel) {
        return TriggerKey.triggerKey(baseLabel.getName() + String.valueOf(baseLabel.getId()), baseLabel.getGroup());
    }

    private JobKey getJobKey(TaskEntity baseLabel) {
        return JobKey.jobKey(baseLabel.getName() + String.valueOf(baseLabel.getId()), baseLabel.getGroup());
    }
}
